package comptadub

class PresenceController {

	def grailsApplication
	
    def exportService
    def membreService
    def compteService
    def envoiMailService

    static allowedMethods = [save: "POST", update: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        flash.objet = params.objet
        flash.membre = params.membre

        if (!params.max) params.max = 10
        if (!params.sort) params.sort = "id"
        if (!params.order) params.order = "desc"
        if (!flash.membre) flash.membre = session.idMembre.toString()
        
        def query = {
            and {
                if(flash.objet) {
                    like("objet", '%' + flash.objet + '%')
                }

                if (flash.membre != '0') {
                    def selMembre = Membre.get(flash.membre.toInteger())
                    eq("membre", selMembre)
                }
            }
        }

        def criteria = Presence.createCriteria()
        def results = criteria.list(params, query)

        [ presenceInstanceList: results ]
    }

    def export = {
        flash.objet = params.objet
        flash.membre = params.membre
        params.max = null
        params.offset = null

        if (!params.sort) params.sort = "id"
        if (!params.order) params.order = "desc"
        
        def query = {
            and {
                if(flash.objet) {
                    like("objet", '%' + flash.objet + '%')
                }

                if (flash.membre != '0') {
                    def selMembre = Membre.get(flash.membre.toInteger())
                    eq("membre", selMembre)
                }
            }
        }

        def criteria = Presence.createCriteria()
        def results = criteria.list(params, query)

        if(params?.format && params.format != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.format]
            response.setHeader("Content-disposition", "attachment; filename=presence.${params.extension}")
            List fields = ["membre.nom", "debit", "nbPersonne", "nbJour", "dateDepart", "dateArrivee", "objet", "commentaire"]
            Map labels = ["membre.nom": "membre", "debit": "montant"]
            exportService.export(params.format, response.outputStream, results, fields, labels, [:], [:])
        }
    }

    def create = {
        def presenceInstance = new Presence()
        presenceInstance.membre = Membre.get(session.idMembre.toString())
        presenceInstance.properties = params
        return [presenceInstance: presenceInstance]
    }

    def save = {
        def presenceInstance = new Presence(params)
        compteService.calculerMontant(presenceInstance)
        compteService.definirObjet(presenceInstance)
        
        if (presenceInstance.save(flush: true)) {
            membreService.calculerSolde(presenceInstance.membre?.id)

            envoiMail(presenceInstance, "ajoutée")
            
            flash.message = "${message(code: 'presence.created.message')}"
            redirect(action: "show", id: presenceInstance.id)
        }
        else {
            render(view: "create", model: [presenceInstance: presenceInstance])
        }
    }

    def show = {
        def presenceInstance = Presence.get(params.id)
        if (!presenceInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'presence.label', default: 'Presence'), params.id])}"
            redirect(action: "list")
        }
        else {
            [presenceInstance: presenceInstance]
        }
    }

    def edit = {
        def presenceInstance = Presence.get(params.id)
        if (!presenceInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'presence.label', default: 'Presence'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [presenceInstance: presenceInstance]
        }
    }

    def update = {
        def presenceInstance = Presence.get(params.id)

        if (presenceInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (presenceInstance.version > version) {
                    presenceInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'presence.label', default: 'Presence')] as Object[], "Another user has updated this Presence while you were editing")
                    render(view: "edit", model: [presenceInstance: presenceInstance])
                    return
                }
            }
            presenceInstance.properties = params
            compteService.calculerMontant(presenceInstance)
            compteService.definirObjet(presenceInstance)
            
            if (!presenceInstance.hasErrors() && presenceInstance.save(flush: true)) {
                membreService.calculerSolde(presenceInstance.membre?.id)

                envoiMail(presenceInstance, "modifiée")
                
                flash.message = "${message(code: 'presence.updated.message')}"
                redirect(action: "show", id: presenceInstance.id)
            }
            else {
                render(view: "edit", model: [presenceInstance: presenceInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'presence.label', default: 'Presence'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def presenceInstance = Presence.get(params.id)
        if (presenceInstance) {
            try {
                presenceInstance.delete(flush: true)
                membreService.calculerSolde(presenceInstance.membre?.id)
                
                envoiMail(presenceInstance, "supprimée")

                flash.message = "${message(code: 'presence.deleted.message')}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'presence.label', default: 'Presence'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'presence.label', default: 'Presence'), params.id])}"
            redirect(action: "list")
        }
    }

    def private envoiMail(Presence presenceInstance, String action) {
        def membre = Membre.get(presenceInstance?.membre?.id.toInteger())
        def sujet = g.message(code:"mail.subject")
        def corps = g.message(code:"mail.body",
                              args:[  action,
                                      membre.nom,
                                      presenceInstance.dateArrivee,
                                      presenceInstance.dateDepart,
                                      presenceInstance.nbJour,
                                      presenceInstance.nbPersonne,
                                      presenceInstance.debit,
                                      presenceInstance.commentaire])

        envoiMailService.envoiMail(membre.email, sujet, corps)
    }
}
